package com.zf.yichat.controller.video;

import com.github.pagehelper.PageHelper;
import com.zf.yichat.controller.BaseController;
import com.zf.yichat.dto.response.VideoCommentDto;
import com.zf.yichat.dto.response.VideoDto;
import com.zf.yichat.mapper.VideoCommentMapper;
import com.zf.yichat.mapper.VideoMapper;
import com.zf.yichat.mapper.VideoTagMapper;
import com.zf.yichat.model.*;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.SysDictService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.service.VideoService;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.DictKey;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 17:52 2019/9/2 2019
 */
@Controller
public class VideoController extends BaseController {

    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private VideoTagMapper videoTagMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private VideoCommentMapper videoCommentMapper;


    @Autowired
    private BalanceService balanceService;

    @Autowired
    private SysDictService sysDictService;

    @RequestMapping("video/index")
    public String userIndex() {
        return "video/index";
    }

    @RequestMapping("video/list")
    @ResponseBody
    public FsResponse userList(Integer page, Integer limit, Long userId, Integer status, Integer type) {

        Example example = new Example(Video.class);
        Example.Criteria criteria = example.createCriteria();
        if (Objects.nonNull(status)) {
            criteria.andEqualTo("status", status);
        } else {
            //criteria.andGreaterThan("status", 0);
        }

        example.setOrderByClause(" id desc");
        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(videoMapper.selectByExample(example), copy -> {
            VideoDto dto = new VideoDto();
            dto.setId(copy.getId());
            dto.setContent(copy.getContent());
            dto.setPath(copy.getPath());
            dto.setThumbnail(copy.getThumbnail());
            dto.setRate(copy.getRate());
            dto.setSeconds(copy.getSeconds());
            dto.setPraiseCount(copy.getPraiseCount());
            dto.setCommentCount(copy.getCommentCount());
            dto.setViewCount(copy.getViewCount());
            dto.setStatus(copy.getStatus());
            dto.setUserId(copy.getUserId());
            dto.setCtime(copy.getCtime());
            dto.setTag(copy.getTag());
            dto.setTitle(copy.getTitle());
            dto.setLinkUrl(copy.getLinkUrl());
            dto.setGoodsImg(copy.getGoodsImg());
            dto.setDiscountInfo(copy.getDiscountInfo());
            dto.setGoodsPrice(copy.getGoodsPrice());
            dto.setSales(copy.getSales());
            dto.setSort(copy.getSort());

            dto.setNick(userService.selectById(copy.getUserId()).getNick());

            return dto;
        });
    }

    @RequestMapping("video/check")
    @ResponseBody
    public FsResponse receiveIndex(Long id, Integer status) {


        Video video = new Video();
        video.setId(id);
        video.setStatus(status);
        video.setCheckTime(new Date());
//        //审核通过增加奖励
//        if (status == 1) {
//            Video src = videoMapper.selectByPrimaryKey(id);
//            BigDecimal reward = new BigDecimal(sysDictService.selectOne(DictKey.video_public_reward).getValue());
//            BigDecimal limit = new BigDecimal(sysDictService.selectOne(DictKey.video_public_reward_limit).getValue());
//            //计算今天是否已经超过奖励
//            Example example = new Example(Video.class);
//            example.createCriteria().andEqualTo("userId", src.getUserId())
//                    .andEqualTo("balanceStatus", 1)
//                    .andGreaterThan("checkTime", DateUtils.formatCurrentDate("yyyy-MM-dd") + DateUtils.TIME_START_SUFFIX)
//                    .andLessThan("checkTime", DateUtils.formatCurrentDate("yyyy-MM-dd") + DateUtils.TIME_END_SUFFIX);
//
//            BigDecimal all = videoMapper.selectByExample(example).stream().map(Video::getBalanceMoney).collect(reducing(BigDecimal.ZERO, BigDecimal::add));
//
//            if ((all.add(reward)).compareTo(limit) <= 0) {
//                video.setBalanceStatus(1);
//                video.setBalanceMoney(reward);
//                balanceService.update(src.getUserId(), BalanceType.VIDEO_PUBLISH, reward, id, "发布视频奖励");
//            }
//
//
//        }

        videoMapper.updateByPrimaryKeySelective(video);

        return FsResponseGen.success();
    }

    @RequestMapping("video/delete")
    @ResponseBody
    public FsResponse delete(Long id) {

        videoService.deleteVideo(id, null);
        return FsResponseGen.success();
    }


    @RequestMapping("video/comment/index")
    public String commentIndex() {
        return "video/comment/index";
    }

    @RequestMapping("video/comment/list")
    @ResponseBody
    public FsResponse commentList(Integer page, Integer limit, Long videoId, String name) {

        Example example = new Example(VideoComment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", 0);
        if (Objects.nonNull(name)) {
            criteria.andLike("content", "%" + name + "%");
        }

        example.setOrderByClause(" id desc");
        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(videoCommentMapper.selectByExample(example), copy -> {
            VideoCommentDto dto = new VideoCommentDto();
            dto.setId(copy.getId());
            dto.setVideoId(copy.getVideoId());
            dto.setUserId(copy.getUserId());
            dto.setSrcCommentId(copy.getSrcCommentId());
            dto.setCommentId(copy.getCommentId());
            dto.setCommentUserId(copy.getCommentUserId());
            dto.setContent(copy.getContent());
            dto.setPraiseCount(copy.getPraiseCount());
            dto.setReplyCount(copy.getReplyCount());
            dto.setBalanceStatus(copy.getBalanceStatus());
            dto.setStatus(copy.getStatus());
            dto.setCtime(copy.getCtime());


            dto.setNick(userService.selectById(copy.getUserId()).getNick());

            return dto;
        });
    }


    @RequestMapping("video/comment/delete")
    @ResponseBody
    public FsResponse commentDelete(Long id) {

        videoService.deleteComment(id, null);
        return FsResponseGen.success();
    }


    @RequestMapping("video/reward/index")
    public String rewardIndex() {

        getRequest().setAttribute("content", sysDictService.selectOne(DictKey.video_reward_memo).getMemo());
        return "video/reward/index";
    }

    @RequestMapping("video/reward")
    @ResponseBody
    public FsResponse reward(String content) {


        SysDict dict = sysDictService.selectOne(DictKey.video_reward_memo);
        dict.setMemo(content);
        dict.setValue(String.valueOf(org.apache.commons.lang3.math.NumberUtils.toLong(dict.getValue()) + 1));
        sysDictService.save(dict, null);

        return FsResponseGen.success();
    }

    @RequestMapping("video/save/index")
    public String saveIndex(Long id) {
        getRequest().setAttribute("video", Objects.nonNull(id) ? videoService.selectById(id) : null);

        return "video/save";
    }

    @RequestMapping("video/save")
    @ResponseBody
    public FsResponse save(Video video) {

        Contracts.assertTrue(Objects.nonNull(video.getId()), "视频不存在");
        videoMapper.updateByPrimaryKeySelective(video);
        return FsResponseGen.success();
    }

    @RequestMapping("video/tag/index")
    public String tagIndex() {
        return "video/tag/index";
    }

    @RequestMapping("video/tag/list")
    @ResponseBody
    public FsResponse listTag(String name) {
        if (Objects.nonNull(name)) {
            Example example = new Example(VideoTag.class);
            example.createCriteria().andLike("name", "%" + name + "%");
            return FsResponseGen.successData(videoTagMapper.selectByExample(example));
        } else {
            return FsResponseGen.successData(videoTagMapper.selectAll());
        }
    }

    @RequestMapping("video/tag/save")
    @ResponseBody
    public FsResponse saveTag(VideoTag tag) {
        Example example = new Example(VideoTag.class);
        example.createCriteria().andEqualTo("name", tag.getName());
        VideoTag tag2 = videoTagMapper.selectOneByExample(example);

        if (Objects.nonNull(tag2)) {
            return FsResponseGen.failMsg("该标签已存在");
        }

        if (Objects.isNull(tag.getId())) {
            videoTagMapper.insert(tag);
        } else {
            videoTagMapper.updateByPrimaryKey(tag);
        }
        return FsResponseGen.success();
    }

    @RequestMapping("video/tag/delete")
    @ResponseBody
    public FsResponse delateTag(Long id) {
        videoTagMapper.deleteByPrimaryKey(id);
        return FsResponseGen.success();
    }

}
